<template>
	<view>
		<view class="cu-card case " style="margin-top: 32rpx;">
			<view class="cu-item shadow ">
				<view class="">
					<uni-section class="mb-10" :title="'商品基本信息'" type="line" titleFontSize='16px'> </uni-section>
				</view>
				<uni-easyinput :inputBorder="false" :trim='true' :clearable='true' v-model="from.title"
					placeholder="请输入商品名称"></uni-easyinput>
				<view class="" style="padding: 24rpx ;border-top: 1px solid #ccc;">
					<uni-easyinput :inputBorder="false" :trim='true' :maxlength='-1' v-model="from.content"
						:clearable='true' type="textarea" autoHeight placeholder="请输入商品描述"></uni-easyinput>
					<uni-file-picker limit="6" title="添加商品图片" v-model="from.images" :image-styles="imgStyle"
						@select="uploadImages"></uni-file-picker>
				</view>
			</view>
		</view>

		<view class="cu-card case " style="margin-top: 32rpx;overflow:visible">
			<view class="cu-item shadow " style="overflow:visible">
				<view class="">
					<uni-section class="mb-10" :title="'商品详情'" type="line" titleFontSize='16px'></uni-section>
				</view>
				<view class="pire_box flex justify-start align-center" style="font-size: 16px;">
					<view class="" style="margin-right: 20rpx;font-size: 16px;">
						新旧程度
					</view>
					<uni-data-select style="width: 60%;" placement="top" v-model="from.idleInfo.condition"
						:clear="false" :localdata="rangeType" @change="change"></uni-data-select>
				</view>

				<view class="pire_box flex justify-start align-center" style="font-size: 16px;">
					<view class="" style="margin-right: 20rpx;font-size: 16px;">
						原价
					</view>
					<uni-easyinput :inputBorder="false" v-model="from.idleInfo.originalPrice"
						placeholder="最多保留两位小数"></uni-easyinput>
				</view>
				<view class="pire_box flex justify-start align-center" style="font-size: 16px;">
					<view class="" style="margin-right: 20rpx;">
						现价
					</view>
					<uni-easyinput :inputBorder="false" v-model="from.idleInfo.price"
						placeholder="最多保留两位小数"></uni-easyinput>
				</view>

			</view>
		</view>
		<view class="release_btn" style="margin-top: 32rpx;">
			<button type="warn" @click="releaseCircle">发布</button>
		</view>
	</view>


</template>

<script>
	import {
		addNormal,
		editNormal
	} from "@/api/circle.js"
	import storage from "@/utils/storage.js";
	import config from '@/config/config';
	export default {
		props: ['circleInfo'],
		data() {
			return {
				config,
				rangeType: [{
						value: '全新',
						text: '全新',
					},
					{
						value: '九成新',
						text: '九成新',
					},

					{
						value: '八成新',
						text: '八成新',
					},

					{
						value: '七成新',
						text: '七成新',
					},
					{
						value: '六成新',
						text: '六成新',
					},
					{
						value: '五成新',
						text: '五成新',
					},
					{
						value: '其他',
						text: '其他',
					},
				], //类型下拉框
				imgStyle: {

					"border": { // 如果为 Boolean 值，可以控制边框显示与否
						"color": "#ccc", // 边框颜色
						"radius": "8" // 边框圆角，支持百分比
					}
				},
				circleId: '',
				from: {
					type: '邻里闲置',
					title: '', //物品名称
					content: '', //内容
					idleInfo: {
						originalPrice: '', //原价
						price: '', //现价
						condition: '', //新旧程度
					},
					images: []
				}
			};
		},
		mounted() {
			if (this.circleInfo._id) {
				this.from = { ...this.circleInfo }
				// 确保idleInfo属性存在
				if (!this.from.idleInfo) {
					this.from.idleInfo = {
						originalPrice: '',
						price: '',
						condition: ''
					}
				}
				this.from.images = this.circleInfo.images.map(url => {
					// 确保图片URL是完整的
					const fullUrl = url.startsWith('https') ? url : this.config.commonUrl + url
					const extension = '.' + url.split('.').pop()

					return {
						url: fullUrl,
						extname: extension, // 从 URL 中提取文件扩展名
						fileType: this.getMimeType(extension), // 假设所有图片都是 JPEG 类型，根据实际情况调整
						status: 'success', // 标记为上传成功
						original: false // 标记为非原始文件
					}
				})
			}
		},
		methods: {

			releaseCircle() {
				// 表单验证
				if (!this.from.title || this.from.title.trim() === '') {
					uni.showToast({
						title: "请输入物品名称",
						icon: "error",
					});
					return;
				}
				
				if (!this.from.content || this.from.content.trim() === '') {
					uni.showToast({
						title: "请输入物品描述",
						icon: "error",
					});
					return;
				}
				
				if (this.from.title.trim().length < 2) {
					uni.showToast({
						title: "物品名称至少2个字符",
						icon: "error",
					});
					return;
				}
				
				if (this.from.content.trim().length < 5) {
					uni.showToast({
						title: "物品描述至少5个字符",
						icon: "error",
					});
					return;
				}
				
				// 闲置物品特有字段验证
				if (!this.from.idleInfo.price || this.from.idleInfo.price.trim() === '') {
					uni.showToast({
						title: "请输入现价",
						icon: "error",
					});
					return;
				}
				
				if (!this.from.idleInfo.condition || this.from.idleInfo.condition.trim() === '') {
					uni.showToast({
						title: "请选择新旧程度",
						icon: "error",
					});
					return;
				}
				
				// 价格验证
				const price = parseFloat(this.from.idleInfo.price);
				if (isNaN(price) || price <= 0) {
					uni.showToast({
						title: "请输入有效的价格",
						icon: "error",
					});
					return;
				}
				
				uni.showLoading({
					title: "发布中...",
					mask: true
				})
				if (this.circleInfo._id) {
					let parmas = {}
					parmas.id = this.circleInfo._id
					parmas.data = this.from
					editNormal(parmas).then(res => {
						uni.hideLoading()
						uni.showToast({
							title: "编辑成功",
							icon: "success",
						});
						this.$router.redirectTo({
							url: '/pages/tabBar/circle'
						})
					}).catch(Error => {
						uni.hideLoading()
						console.log(Error);
						uni.showToast({
							title: Error.data?.message || "编辑失败",
							icon: "error",
						});
					})
				} else {
					addNormal(this.from).then(res => {
						uni.hideLoading()
						if (res.data.code === 200) {
							uni.showToast({
								title: "发布成功",
								icon: "success",
							});
							// 发布成功后返回上一页，保持路由栈
							uni.navigateBack({
								delta: 1
							});
						} else {
							uni.showToast({
								title: res.data.message || "发布失败",
								icon: "error",
							});
						}
					}).catch(Error => {
						uni.hideLoading()
						console.log(Error);
						uni.showToast({
							title: Error.data?.message || "发布失败",
							icon: "error",
						});
					})
				}
			},

			change(e) {
				// console.log(e);
				this.from.idleInfo.condition = e
			},
			uploadImages(e) {
				let self = this
				this.tempFilePath = e.tempFilePaths[0]
				if (this.tempFilePath) {
					const token = storage.getAccessToken()
					uni.uploadFile({
						url: `${config.commonApi}/api/upload/wechat-image`,
						filePath: this.tempFilePath,
						name: 'file',
						header: {
							'authorization': token
						},
						success(uploadFileRes) {

							let data = JSON.parse(uploadFileRes.data)
							let imageData = {
								url: data.data.url
							}
							self.from.images.push(imageData)
						}
					})
				}
			},
			getMimeType(extension) {
				const mimeTypes = {
					'jpg': 'image/jpeg',
					'jpeg': 'image/jpeg',
					'png': 'image/png',
					'gif': 'image/gif',
					'webp': 'image/webp',
					'bmp': 'image/bmp',
					'svg': 'image/svg+xml',
					'ico': 'image/x-icon'
				}
				// 将扩展名转换为小写并去除点号
				const ext = extension.toLowerCase().replace('.', '')
				return mimeTypes[ext] || 'image/jpeg' // 默认 MIME 类型
			},
		}
	}
</script>

<style lang="scss" scoped>
	.example-body {
		padding: 24rpx;
	}

	.uni-easyinput__content-textarea {
		padding: 24rpx;
		padding-left: 0;
	}


	.pire_box {
		padding: 24rpx;
	}

	.cu-item {
		margin: 0 !important;
	}

	/deep/.icon-add {
		height: 2px !important;
	}
</style>